/*
 * libmad - MPEG audio decoder library
 * Copyright (C) 2000-2004 Underbit Technologies, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: minimad.c,v 1.4 2004/01/23 09:41:32 rob Exp $
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#include <sys/types.h>
#include <dirent.h>
#include <pthread.h>
#include <string.h>
#include "alsa/asoundlib.h"
#include "../mp3/install/include/mad.h"
#include <signal.h>
#include <errno.h>
#include "../include/ehome.h"
/*
 * This is perhaps the simplest example use of the MAD high-level API.
 * Standard input is mapped into memory via mmap(), then the high-level API
 * is invoked with three callbacks: input, output, and error. The output
 * callback converts MAD's high-resolution PCM samples to 16 bits, then
 * writes them to standard output in little-endian, stereo-interleaved
 * format.
 */

static int decode(unsigned char const *, unsigned long);
snd_pcm_t*             handle=NULL;        //PCI设备句柄
snd_pcm_hw_params_t*   params=NULL;//硬件信息和PCM流配置

int stop = 0;
void sig_close(){
    stop = 1;       
        
}
int set_pcm()
{
    int    rc;     
    int  dir=0;
    int rate = 44100;;                /* 采样频率 44.1KHz*/
    int format = SND_PCM_FORMAT_S16_LE; /*     量化位数 16      */
    int channels = 2;                 /*     声道数 2           */

    rc=snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
    if(rc<0)
    {
        perror("\nopen PCM device failed:");
        exit(1);
    }
    snd_pcm_hw_params_alloca(&params); //分配params结构体

    rc=snd_pcm_hw_params_any(handle, params);//初始化params
    if(rc<0)
    {
        perror("\nsnd_pcm_hw_params_any:");
        exit(1);
    }
    rc=snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED); //硬件设置为交错模式
    if(rc<0)
    {
        perror("\nsed_pcm_hw_set_access:");
        exit(1);

    }

    rc=snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);             //设置16位采样精度  
    if(rc<0)
    {
        perror("snd_pcm_hw_params_set_format failed:");
        exit(1);
    } 

    rc=snd_pcm_hw_params_set_channels(handle, params, channels);  //设置声道,1表示单声>道，2表示立体声
    if(rc<0)
    {
        perror("\nsnd_pcm_hw_params_set_channels:");
        exit(1);
    }    

    rc=snd_pcm_hw_params_set_rate_near(handle, params, &rate, &dir);  //设置>频率
    if(rc<0)
    {
        perror("\nsnd_pcm_hw_params_set_rate_near:");
        exit(1);
    }   

    rc = snd_pcm_hw_params(handle, params);//释放硬件参数变量空间
    if(rc<0)
    {
        perror("\nsnd_pcm_hw_params: ");
        exit(1);
    }


    return 0;              
}


int get_music_name(char *path, int nth, char *buf)
{
    DIR *pdir = NULL;
    struct dirent *ent = NULL;

    pdir = opendir(path);
    if(pdir == NULL)
    {
        perror("opendir");
        return -1;
    }
    
    while((ent=readdir(pdir)) != NULL)
    {
        if(strstr(ent->d_name, ".mp3"))
        {
            if(nth == 0)
            {
                strcpy(buf, path);
                strcat(buf, ent->d_name);
                break;
            }
            else
            {
                nth--;
            }
        }
    }
    closedir(pdir);

    if(ent == NULL)
    {
        return -1;
    }
    else
    {
        return 0;
    }



}
extern pthread_mutex_t lock ;
extern pthread_cond_t  conti;
extern int music_stat;
  

void *music_play(void *p){
    struct stat stat;
    void *fdm;
    int cur_pos=0;
    char buf[1024]={0};

    if(set_pcm()!=0){
        printf("set_pcm failed:\n");
        return NULL;
    }
    signal(SIGINT,sig_close);
    while(!get_music_name("/home/songs/",cur_pos,buf)){
        printf("file name %s:\n",buf);
        int fd=open(buf,O_RDONLY);
        if(fd<0){
        perror("open mp3 files error");
        cur_pos++;
        continue;
        }
        if(fstat(fd,&stat)==-1||stat.st_size==0){
            close(fd);
            cur_pos++;
            continue;
        }
        fdm=mmap(0,stat.st_size,PROT_READ,MAP_SHARED, fd, 0);
        if(fdm==MAP_FAILED){
            close(fd);
            cur_pos++;
            continue;
        }
        decode(fdm,stat.st_size);
        if(munmap(fdm,stat.st_size)==-1){
            close(fd);
            cur_pos++;
            continue;
        }
        pthread_mutex_lock(&lock);
        if(music_stat==0||music_stat==2){
            cur_pos++;
        }else if(music_stat==3){
            cur_pos=cur_pos?(cur_pos-1):0;
        }
        music_stat=0;
        pthread_mutex_unlock(&lock);
    }
    pthread_mutex_lock(&lock);
    music_stat=-1;
    pthread_mutex_unlock(&lock);
    snd_pcm_drain(handle);
    snd_pcm_close(handle);
    return 0;
}

/*
 * This is a private message structure. A generic pointer to this structure
 * is passed to each of the callback functions. Put here any data you need
 * to access from within the callbacks.
 */

struct buffer {
  unsigned char const *start;
  unsigned long length;
};

/*
 * This is the input callback. The purpose of this callback is to (re)fill
 * the stream buffer which is to be decoded. In this example, an entire file
 * has been mapped into memory, so we just call mad_stream_buffer() with the
 * address and length of the mapping. When this callback is called a second
 * time, we are finished decoding.
 */

static
enum mad_flow input(void *data,
		    struct mad_stream *stream)
{
  struct buffer *buffer = data;

  if (!buffer->length)
    return MAD_FLOW_STOP;

  mad_stream_buffer(stream, buffer->start, buffer->length);

  buffer->length = 0;

  return MAD_FLOW_CONTINUE;
}

/*
 * The following utility routine performs simple rounding, clipping, and
 * scaling of MAD's high-resolution samples down to 16 bits. It does not
 * perform any dithering or noise shaping, which would be recommended to
 * obtain any exceptional audio quality. It is therefore not recommended to
 * use this routine if high-quality output is desired.
 */

static inline
signed int scale(mad_fixed_t sample)
{
  /* round */
  sample += (1L << (MAD_F_FRACBITS - 16));

  /* clip */
  if (sample >= MAD_F_ONE)
    sample = MAD_F_ONE - 1;
  else if (sample < -MAD_F_ONE)
    sample = -MAD_F_ONE;

  /* quantize */
  return sample >> (MAD_F_FRACBITS + 1 - 16);
}
/*
 * This is the output callback function. It is called after each frame of
 * MPEG audio data has been completely decoded. The purpose of this callback
 * is to output (or play) the decoded PCM audio.
 */

static
enum mad_flow output(void *data,
             struct mad_header const *header,
             struct mad_pcm *pcm)
{
  unsigned int nchannels, nsamples,n;
  mad_fixed_t const *left_ch, *right_ch;
  unsigned char Output[6912], *OutputPtr;  
  pthread_mutex_lock(&lock);
  if(music_stat == 1)
  {
      /*当前线程睡眠*/
      printf("recv pasue sleep....\n");
    //snd_pcm_pause(handle, 1);
    snd_pcm_drop(handle);
      pthread_cond_wait(&conti, &lock);
      
      //while(snd_pcm_resume(handle) == -EAGAIN) sleep(1);
      //snd_pcm_pause(handle, 0);
      snd_pcm_prepare(handle);
      printf("recv paly go on ....\n");
  }
  else if(music_stat == 2 || music_stat == 3)
  {
      pthread_mutex_unlock(&lock);
      return MAD_FLOW_STOP;
  }

  pthread_mutex_unlock(&lock);
  /* pcm->samplerate contains the sampling frequency */

  nchannels = pcm->channels;
  n=nsamples  = pcm->length;
  left_ch   = pcm->samples[0];
  right_ch  = pcm->samples[1];
  
  
   OutputPtr = Output;  
   
   while (nsamples--) 
   {
    signed int sample;

    /* output sample(s) in 16-bit signed little-endian PCM */
    
    sample = scale(*left_ch++);
   
    *(OutputPtr++) = sample >> 0;  
    *(OutputPtr++) = sample >> 8;  
    if (nchannels == 2)  
        {  
            sample = scale (*right_ch++);  
            *(OutputPtr++) = sample >> 0;  
            *(OutputPtr++) = sample >> 8;  
        }  
    
  
  }
    OutputPtr = Output; 
    //写数据帧到PCM
    snd_pcm_writei (handle, OutputPtr, n);  
    OutputPtr = Output;     
if(stop == 0)
  return MAD_FLOW_CONTINUE;
else
    return  MAD_FLOW_STOP;
}

static
enum mad_flow error(void *data,
		    struct mad_stream *stream,
		    struct mad_frame *frame)
{
  struct buffer *buffer = data;

  fprintf(stderr, "decoding error 0x%04x (%s) at byte offset %u\n",
	  stream->error, mad_stream_errorstr(stream),
	  stream->this_frame - buffer->start);

  /* return MAD_FLOW_BREAK here to stop decoding (and propagate an error) */

  return MAD_FLOW_CONTINUE;
}

/*
 * This is the function called by main() above to perform all the decoding.
 * It instantiates a decoder object and configures it with the input,
 * output, and error callback functions above. A single call to
 * mad_decoder_run() continues until a callback function returns
 * MAD_FLOW_STOP (to stop decoding) or MAD_FLOW_BREAK (to stop decoding and
 * signal an error).
 */

static
int decode(unsigned char const *start, unsigned long length)
{
  struct buffer buffer;
  struct mad_decoder decoder;
  int result;

  /* initialize our private message structure */

  buffer.start  = start;
  buffer.length = length;

  /* configure input, output, and error functions */

  mad_decoder_init(&decoder, &buffer,
		   input, 0 /* header */, 0 /* filter */, output,
		   error, 0 /* message */);

  /* start decoding */

  result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);

  /* release the decoder */

  mad_decoder_finish(&decoder);

  return result;
}
